package com.pan.creational.abstractfactory.utils;

import org.w3c.dom.Element;

import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import java.lang.reflect.InvocationTargetException;

public enum AbstractFactoryUtils {
    INSTANCE;

    private Element rootElement;

    {
        File file = new File(//System.getProperty("user.dir")+
                "src\\main\\java\\com\\pan\\creational\\abstractfactory\\config.xml");
        try {
            rootElement = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(file).getDocumentElement();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        rootElement.normalize();
    }

    public String getClassname(String nodeName){
        return getElement(nodeName)
                .getTextContent()
                .strip();
    }

    public Element getElement(String nodeName){
        return (Element) rootElement
                .getElementsByTagName(nodeName).item(0);
    }

    public Object getObjectByXMLNodeName(String nodeName){
        String className = getClassname(nodeName);
        Object o = null;
        try {
            o = Class.forName(className).getConstructor().newInstance();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return o;

    }
}
